Recette n 59 Rcuprer une copie dun fichier sur Google Drive
Page 189


private FileList cachedList = null;
private java.util.Date cacheDate = null;
private File openOrCreateFileWithName(String n) throws IOException {
   FileList existingFiles = null;

   if(cachedList == null || cacheDate == null || Math.abs(cacheDate.getTime() - (new java.util.Date()).getTime()) > 5 * 60000) { // 5 min
      existingFiles = service.files().list().execute();
      cachedList = existingFiles;
      cacheDate = new java.util.Date();
   } else {
      existingFiles = cachedList;
   }

   boolean exists = false;
   for(File ef : existingFiles.getItems()) {
      if(ef.getTitle().contentEquals(n)) {
         exists = true;
         break;
      }

   }

   if(!exists) {
      File body = new File();
      body.setTitle(n);
      body.setMimeType("plain/text");
      File f = service.files().insert(body).execute();

      existingFiles = service.files().list().execute();
      cachedList = existingFiles;
      cacheDate = new java.util.Date();
   }

   File file = null;

   for(File ef : existingFiles.getItems()) {
      if(ef.getTitle().contentEquals(n)) {
         file = ef;
         break;
      }

   }

   return file;
}

private void readFileFromDrive() {
   Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
         try {
            File file = openOrCreateFileWithName("Dunod");

            if(file != null) {
               String durl = file.getDownloadUrl();
               final String contents = readContentsOfFile(file);

               if(contents != null) {
                  runOnUiThread(new Runnable() {

                     @Override
                     public void run() {
                        ((EditText)findViewById(R.id.textView)).setText(contents);
                     }
                  });
               }
            }
         } catch(Exception e) {
            final String msg = e.getLocalizedMessage();
            runOnUiThread(new Runnable() {

               @Override
               public void run() {
                  ((EditText)findViewById(R.id.textView)).setText("Erreur:\n"+msg);
               }
            });
         }
      }
   });

   t.start();
}
